Java 8 – List分组GroupBy

转载自:http://blog.csdn.net/u013078669/article/details/52717142

1. 分组, 计数和排序

1.1 分组, 计数

[java]  view plain  copy
  1.    public static void main(String[] args) {  
  2.   
  3.     //3 apple, 2 banana, others 1  
  4.     List<string> items =  
  5.             Arrays.asList("apple""apple""banana",  
  6.                     "apple""orange""banana""papaya");  
  7.   
  8.     Map<string long=""> result =  
  9.             items.stream().collect(  
  10.                     Collectors.groupingBy(  
  11.                             Function.identity(), Collectors.counting()  
  12.                     )  
  13.             );  
  14.   
  15.     System.out.println(result);  
  16.   
  17.   
  18. }  
  19. /string></string>  
输出
[text]  view plain  copy
  1. {  
  2.     papaya=1, orange=1, banana=2, apple=3  
  3. }  

1.2 分组, 计数和排序

[java]  view plain  copy
  1.  public static void main(String[] args) {  
  2.   
  3.         //3 apple, 2 banana, others 1  
  4.         List<string> items =  
  5.                 Arrays.asList("apple""apple""banana",  
  6.                         "apple""orange""banana""papaya");  
  7.   
  8.         Map<string long=""> result =  
  9.                 items.stream().collect(  
  10.                         Collectors.groupingBy(  
  11.                                 Function.identity(), Collectors.counting()  
  12.                         )  
  13.                 );  
  14.   
  15.         Map<string long=""> finalMap = new LinkedHashMap<>();  
  16.   
  17.         //Sort a map and add to finalMap  
  18.         result.entrySet().stream()  
  19.                 .sorted(Map.Entry.<string long="">comparingByValue()  
  20.                         .reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));  
  21.   
  22.         System.out.println(finalMap);  
  23.   
  24.   
  25.     }  
  26. </string></string></string></string>  
输出:
[text]  view plain  copy
  1. {  
  2.     apple=3, banana=2, papaya=1, orange=1  
  3. }  

2.用户自定义对象集合分组, 计数、排序和求和

[java]  view plain  copy
  1. public static void main(String[] args) {  
  2.   
  3.        //3 apple, 2 banana, others 1  
  4.        List<item> items = Arrays.asList(  
  5.                new Item("apple"10new BigDecimal("9.99")),  
  6.                new Item("banana"20new BigDecimal("19.99")),  
  7.                new Item("orang"10new BigDecimal("29.99")),  
  8.                new Item("watermelon"10new BigDecimal("29.99")),  
  9.                new Item("papaya"20new BigDecimal("9.99")),  
  10.                new Item("apple"10new BigDecimal("9.99")),  
  11.                new Item("banana"10new BigDecimal("19.99")),  
  12.                new Item("apple"20new BigDecimal("9.99"))  
  13.        );  
  14.   
  15.        Map<string long=""> counting = items.stream().collect(  
  16.                Collectors.groupingBy(Item::getName, Collectors.counting()));  
  17.   
  18.        System.out.println(counting);  
  19.   
  20.        Map<string integer=""> sum = items.stream().collect(  
  21.                Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQty)));  
  22.   
  23.        System.out.println(sum);  
  24.   
  25.    }  
  26. lt;/string></string></item>  
输出
[text]  view plain  copy
  1. //Group by + Count  
  2. {  
  3.     papaya=1, banana=2, apple=3, orang=1, watermelon=1  
  4. }  
  5.   
  6. //Group by + Sum qty  
  7. {  
  8.     papaya=20, banana=30, apple=40, orang=10, watermelon=10  
  9. }  
[java]  view plain  copy
  1. public static void main(String[] args) {  
  2.   
  3.         //3 apple, 2 banana, others 1  
  4.         List<item> items = Arrays.asList(  
  5.                 new Item("apple"10new BigDecimal("9.99")),  
  6.                 new Item("banana"20new BigDecimal("19.99")),  
  7.                 new Item("orang"10new BigDecimal("29.99")),  
  8.                 new Item("watermelon"10new BigDecimal("29.99")),  
  9.                 new Item("papaya"20new BigDecimal("9.99")),  
  10.                 new Item("apple"10new BigDecimal("9.99")),  
  11.                 new Item("banana"10new BigDecimal("19.99")),  
  12.                 new Item("apple"20new BigDecimal("9.99"))  
  13.                 );  
  14.   
  15.         //group by price  
  16.         Map<BigDecimal, List<item>> groupByPriceMap =  
  17.             items.stream().collect(Collectors.groupingBy(Item::getPrice));  
  18.   
  19.         System.out.println(groupByPriceMap);  
  20.   
  21.         // group by price, uses 'mapping' to convert List<item> to Set<string>  
  22.         Map<BigDecimal, Set<string>> result =  
  23.                 items.stream().collect(  
  24.                         Collectors.groupingBy(Item::getPrice,  
  25.                                 Collectors.mapping(Item::getName, Collectors.toSet())  
  26.                         )  
  27.                 );  
  28.   
  29.         System.out.println(result);  
  30.   
  31.     }  
  32. </string></string></item></item></item>  
输出
[text]  view plain  copy
  1. {  
  2.     19.99=[  
  3.             Item{name='banana', qty=20, price=19.99},   
  4.             Item{name='banana', qty=10, price=19.99}  
  5.         ],   
  6.     29.99=[  
  7.             Item{name='orang', qty=10, price=29.99},   
  8.             Item{name='watermelon', qty=10, price=29.99}  
  9.         ],   
  10.     9.99=[  
  11.             Item{name='apple', qty=10, price=9.99},   
  12.             Item{name='papaya', qty=20, price=9.99},   
  13.             Item{name='apple', qty=10, price=9.99},   
  14.             Item{name='apple', qty=20, price=9.99}  
  15.         ]  
  16. }  
  17.   
  18. //group by + mapping to Set  
  19. {  
  20.     19.99=[banana],   
  21.     29.99=[orang, watermelon],   
  22.     9.99=[papaya, apple]  
  23. }  
Java 8中,可以使用Stream对List进行分组,并将结果转换为Map。下面是一个示例代码: ```java import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class GroupingExample { public static void main(String[] args) { // 假设有一个Person类,包含name和age属性 List<Person> personList = List.of( new Person("Alice", 25), new Person("Bob", 30), new Person("Alice", 35), new Person("Charlie", 40) ); // 使用Stream的groupingBy方法进行分组,并将结果转换为Map Map<String, List<Person>> personMap = personList.stream() .collect(Collectors.groupingBy(Person::getName)); // 打印分组结果 personMap.forEach((name, group) -> { System.out.println(name + ": " + group); }); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ``` 在上述示例中,我们首先定义了一个Person类,包含name和age属性。然后,我们创建了一个包含Person对象的List。 接下来,在使用Stream的`groupingBy`方法时,我们传递了一个函数`Person::getName`作为分组的依据,它将根据Person对象的name属性进行分组。最后,通过`collect(Collectors.groupingBy())`将分组结果转换为Map。 最后,我们使用`forEach`方法遍历Map,并打印分组结果。输出结果如下: ``` Alice: [Person{name='Alice', age=25}, Person{name='Alice', age=35}] Bob: [Person{name='Bob', age=30}] Charlie: [Person{name='Charlie', age=40}] ``` 以上是一个简单的示例,你可以根据自己的需求进行适当的修改和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值